<template>
  <div id="mapContainer"></div>
</template>

<script setup>
import { onMounted, nextTick, ref, watchEffect, watch, defineEmits } from "vue";
import { Map, View } from "ol";

import {
  defaults as defaultControls,
  ZoomSlider,
  ZoomToExtent,
} from "ol/control";

import Collection from "ol/Collection";

import { transform } from "ol/proj";
import { register } from "ol/proj/proj4";
import proj4 from "proj4";

import { tdt_api_key /** 天地图的key */ } from "@/config/keys.json";
import { addTdtBaseLayer } from "@/utils/baseMap.js";
import { getDefaultControls } from "@/utils/controls";

const { projection, center, zoom, attribution } = defineProps({
  projection: {
    type: String,
    default: "EPSG:4326",
  },
  center: {
    type: Array,
    default: [113.17756338652154, 23.701191837626297],
  },
  zoom: {
    type: Number,
    default: 12,
  },

  attribution: {
    type: String,
    default: "",
  },
});

const $emit = defineEmits(["loadend"]);

function handClick() {
  emit("submit");
}

function initMap() {
  proj4.defs(
    "EPSG:4547",
    "+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs"
  );

  let center_ =
    projection === "EPSG:4326"
      ? center
      : transform(center, "EPSG:4326", projection);

  register(proj4);

  // 控件列表

  const map = new Map({
    view: new View({
      projection,
      center: center_,
      zoom,
      constrainResolution: true,
    }),
    target: "mapContainer",
    controls: getDefaultControls(attribution),
    layers: [addTdtBaseLayer(tdt_api_key, "vec", "c", "wmts")],
  });

  // 加载底图
  // addTdtBaseLayer(map, tdt_api_key, "vec", "c", "wmts");
  window.map = map;

  //地图点击事件
  map.on("click", e => {
    // console.log("click", e.coordinate);
    // console.log("zoom", map.getView().getZoom());
    // console.log("resolution", map.getView().getResolution());
  });

  $emit("loadend", map);
}

onMounted(() => {
  nextTick(() => {
    initMap();
  });
});
</script>

<style lang="less" scoped>
#mapContainer {
  width: 100%;
  height: 99vh;
}
</style>
